﻿using Microsoft.Extensions.Caching.Memory;

namespace HomeCloudStorageSystem.Middleware
{
    /// <summary>
    /// 身份验证中间件
    /// </summary>
    public class AuthMiddleware
    {
        public readonly IMemoryCache _memoryCache;
        private readonly RequestDelegate _next;

        public AuthMiddleware(IMemoryCache memoryCache, RequestDelegate next)
        {
            _memoryCache = memoryCache;
            _next = next;
        }
        public Task Invoke(HttpContext httpContext)
        {
            List<string> routersNotLogin = new List<string>()
            {
                "/api/Auth/login",   
                "/api/Auth/register"
            };
            bool isSu = _memoryCache.TryGetValue("user_key", out string value);
            if (!isSu && !routersNotLogin.Contains(httpContext.Request.Path))
            {
                httpContext.Response.WriteAsync("用户未登录");
                return Task.CompletedTask;
            }
            return _next(httpContext);
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class AuthMiddlewareExtensions
    {
        public static IApplicationBuilder UseAuthMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<AuthMiddleware>();
        }
    }
}
